package com.code.common.web.interceptors;

import com.code.common.annotations.LoginAuth;
import com.code.common.enums.ResultCode;
import com.code.common.exceptions.BusinessException;
import com.code.common.util.StringUtil;
import com.code.user.model.bo.LoginTokenBO;
import com.code.user.token.helper.LoginTokenHelper;
import com.code.user.token.service.LoginTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 已登录权限验证拦截器 备注：通过{@link LoginAuth}配合使用
 *
 * @author tangyifei
 */
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private LoginTokenService loginTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();

            if (clazz.isAnnotationPresent(LoginAuth.class) || method.isAnnotationPresent(LoginAuth.class)) {

                //获取登录TOKEN ID
                String loginTokenId = LoginTokenHelper.getLoginTokenId();
                log.info("登陆的tokenId：{}", loginTokenId);
                if (StringUtil.isEmpty(loginTokenId)) {
                    throw new BusinessException(ResultCode.USER_ERROR_20001);
                }

                //获取登录TOKEN信息
                LoginTokenBO loginToken = loginTokenService.getById(loginTokenId);
                if (null == loginToken) {
                    throw new BusinessException(ResultCode.USER_ERROR_20001);
                }

                return true;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // nothing to do
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // nothing to do
    }

}
